﻿using System;
using System.Collections.Generic;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Linq;


namespace gpuHough.DirectX
{
    public interface IShape
    {
        void RenderShape(Device device);
    }

    abstract partial class Shape<VertexType> : IShape
        where VertexType : struct
    {
        //helper
        protected Vector3 Vector2ToVector3(Vector2 vector)
        {
            return new Vector3(vector.X, vector.Y, 0);
        }
        
        private VertexBuffer vertexBuffer;
        private int trianglesCount = 0;
        private VertexBuffer GetVertexBuffer(Device device)
        {
            if (vertexBuffer == null)
            {
                VertexType[] triangleVertices = BuildShape();
                vertexBuffer = new VertexBuffer(typeof(VertexType), triangleVertices.Length, device, Usage.None, GetVertexFormat(), Pool.Managed);
                trianglesCount = triangleVertices.Length / 3;
                vertexBuffer.SetData(triangleVertices, 0, LockFlags.Discard);
            }
            
            return vertexBuffer;
        }

        public abstract VertexFormats GetVertexFormat();
        public abstract VertexType[] BuildShape();

        public void RenderShape(Device device)
        {
            device.VertexFormat = GetVertexFormat();
            device.SetStreamSource(0, GetVertexBuffer(device), 0);

            device.DrawPrimitives(PrimitiveType.TriangleList, 0, trianglesCount);
            
        }
    }
}
